package com.bodsite.rpc.thrift.server;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;

import com.bodsite.common.logger.Logger;
import com.bodsite.common.logger.LoggerFactory;
import com.bodsite.common.utils.IpUtil;
import com.bodsite.rpc.spring.schema.bean.Module;
import com.bodsite.rpc.spring.schema.bean.Service;
import com.bodsite.rpc.spring.schema.bean.Zookeeper;
import com.bodsite.rpc.thrift.constant.ThriftConstant;
import com.bodsite.rpc.thrift.zk.BaseZkClient;

/**
 * 服务注册
 * @author bod
 * 2017年4月13日上午10:22:02
 */
public class ServiceRegistry extends BaseZkClient{
	private static final Logger logger = LoggerFactory.getLogger(ServiceRegistry.class);
	private final Service service;
	private final String groupPath;
	private final String modulePath;
	private final String servicePath;
	
	public ServiceRegistry(Service service, Module module, Zookeeper zookeeper){
		this.service = service;
		this.groupPath = ThriftConstant.SERVICE_HOME+"/"+zookeeper.getGroup();
		this.modulePath = this.groupPath+"/"+module.getVersion();
		this.servicePath = this.modulePath+"/"+service.getId();
		this.zookeeperHost = zookeeper.getAddress();
	}

	@Override
	public void nodeChildrenChanged(WatchedEvent event) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void connected(WatchedEvent event) {
		//获取本机ip地址
		String ip = IpUtil.getLocalIp();
		try {
			createBaseNode();
			String serverAddress = ip+":"+service.getPort();
			String createdPath = createEphemeralNode(servicePath+"/"+serverAddress, serverAddress.getBytes("utf-8"));
			logger.info(" zk registry succss ! "+createdPath);
		} catch (Exception e) {
			logger.error(" zk registry error ! "+service.getId(),e);
		}
		
	}
	
	/**
	 * 创建service基础节点
	 * @author bod
	 * 2017年4月12日下午5:11:01
	 */
	private void createBaseNode() throws KeeperException, InterruptedException{
		if(!exists(ThriftConstant.BASE_HOME, false)){
			createPersistentNode(ThriftConstant.BASE_HOME, null);
		}
		if(!exists(ThriftConstant.SERVICE_HOME, false)){
			createPersistentNode(ThriftConstant.SERVICE_HOME, null);
		}
		if(!exists(groupPath, false)){//环境
			createPersistentNode(groupPath, null);
		}
		if(!exists(modulePath, false)){//应用模块名
			createPersistentNode(modulePath, null);
		}
		if(!exists(servicePath, false)){//服务名
			createPersistentNode(servicePath, null);
		}
	}
}
